/**
 * 账号服务
 * 提供账号的增删改查功能
 */

import { StorageKeys, getStorageSync, setStorageSync } from './storage.js';

/**
 * 生成随机颜色（用于账号图标）
 * @returns {string} 颜色值
 */
function generateColor() {
	const colors = [
		'#FF9500', '#1E88E5', '#FFC107', '#4CAF50', 
		'#F44336', '#9C27B0', '#00BCD4', '#FF5722',
		'#795548', '#607D8B', '#E91E63', '#3F51B5'
	];
	return colors[Math.floor(Math.random() * colors.length)];
}

/**
 * 格式化日期时间
 * @param {Date|string} date 日期对象或字符串
 * @returns {string} 格式化后的日期时间字符串
 */
function formatDateTime(date) {
	const d = date instanceof Date ? date : new Date(date);
	const year = d.getFullYear();
	const month = String(d.getMonth() + 1).padStart(2, '0');
	const day = String(d.getDate()).padStart(2, '0');
	const hour = String(d.getHours()).padStart(2, '0');
	const minute = String(d.getMinutes()).padStart(2, '0');
	const second = String(d.getSeconds()).padStart(2, '0');
	return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

/**
 * 获取所有账号
 * @returns {Array} 账号列表
 */
export function getAllAccounts() {
	const accounts = getStorageSync(StorageKeys.ACCOUNTS, []);
	return Array.isArray(accounts) ? accounts : [];
}

/**
 * 根据ID获取账号
 * @param {number} id 账号ID
 * @returns {Object|null} 账号对象
 */
export function getAccountById(id) {
	const accounts = getAllAccounts();
	return accounts.find(account => account.id === id) || null;
}

/**
 * 根据标签筛选账号
 * @param {string} tagName 标签名称
 * @returns {Array} 账号列表
 */
export function getAccountsByTag(tagName) {
	const accounts = getAllAccounts();
	return accounts.filter(account => account.tag === tagName);
}

/**
 * 获取收藏的账号
 * @returns {Array} 账号列表
 */
export function getFavoriteAccounts() {
	const accounts = getAllAccounts();
	return accounts.filter(account => account.isFavorite === true);
}

/**
 * 搜索账号
 * @param {string} keyword 搜索关键词
 * @returns {Array} 账号列表
 */
export function searchAccounts(keyword) {
	if (!keyword || keyword.trim() === '') {
		return getAllAccounts();
	}

	const accounts = getAllAccounts();
	const lowerKeyword = keyword.toLowerCase().trim();

	return accounts.filter(account => {
		return (
			(account.name && account.name.toLowerCase().includes(lowerKeyword)) ||
			(account.account && account.account.toLowerCase().includes(lowerKeyword)) ||
			(account.subtitle && account.subtitle.toLowerCase().includes(lowerKeyword)) ||
			(account.note && account.note.toLowerCase().includes(lowerKeyword))
		);
	});
}

/**
 * 添加账号
 * @param {Object} accountData 账号数据
 * @param {string} accountData.name 账号名称（必填）
 * @param {string} accountData.account 账号/用户名
 * @param {string} accountData.password 密码
 * @param {string} accountData.note 备注
 * @param {string} accountData.tag 标签
 * @param {boolean} accountData.isFavorite 是否收藏
 * @param {string} accountData.color 图标颜色
 * @returns {Object} 新创建的账号对象
 */
export function addAccount(accountData) {
	if (!accountData || !accountData.name || accountData.name.trim() === '') {
		throw new Error('账号名称不能为空');
	}

	const accounts = getAllAccounts();
	
	// 获取或初始化计数器
	let counter = getStorageSync(StorageKeys.ACCOUNT_COUNTER, 0);
	counter += 1;

	const now = new Date();
	// 处理标签：如果为空，则不保存标签
	const tagValue = accountData.tag || '';
	const finalTag = tagValue.trim() !== '' ? tagValue : '';
	
	const newAccount = {
		id: counter,
		name: accountData.name.trim(),
		account: accountData.account || '',
		password: accountData.password || '',
		note: accountData.note || '',
		tag: finalTag,
		isFavorite: accountData.isFavorite || false,
		color: accountData.color || generateColor(),
		subtitle: accountData.account || accountData.subtitle || '',
		category: accountData.category || 'all',
		customFields: accountData.customFields || {}, // 保存自定义字段
		createdAt: now.toISOString(),
		updatedAt: now.toISOString(),
		lastModified: formatDateTime(now)
	};

	accounts.push(newAccount);

	// 保存账号列表和计数器
	setStorageSync(StorageKeys.ACCOUNT_COUNTER, counter);
	setStorageSync(StorageKeys.ACCOUNTS, accounts);

	return newAccount;
}

/**
 * 更新账号
 * @param {number} id 账号ID
 * @param {Object} accountData 要更新的账号数据
 * @returns {Object|null} 更新后的账号对象
 */
export function updateAccount(id, accountData) {
	const accounts = getAllAccounts();
	const accountIndex = accounts.findIndex(account => account.id === id);

	if (accountIndex === -1) {
		throw new Error('账号不存在');
	}

	const existingAccount = accounts[accountIndex];
	const now = new Date();

	// 处理标签：如果为空，则不保存标签
	if (accountData.tag !== undefined) {
		const tagValue = accountData.tag || '';
		accountData.tag = tagValue.trim() !== '' ? tagValue : '';
	}

	const updatedAccount = {
		...existingAccount,
		...accountData,
		id: id, // 确保ID不被修改
		updatedAt: now.toISOString(),
		lastModified: formatDateTime(now)
	};

	// 如果更新了账号字段，同时更新subtitle
	if (accountData.account !== undefined) {
		updatedAccount.subtitle = accountData.account;
	}

	// 如果名称被修改，确保不为空
	if (accountData.name !== undefined) {
		if (!accountData.name || accountData.name.trim() === '') {
			throw new Error('账号名称不能为空');
		}
		updatedAccount.name = accountData.name.trim();
	}

	accounts[accountIndex] = updatedAccount;
	setStorageSync(StorageKeys.ACCOUNTS, accounts);

	return updatedAccount;
}

/**
 * 删除账号
 * @param {number} id 账号ID
 * @returns {boolean} 是否删除成功
 */
export function deleteAccount(id) {
	const accounts = getAllAccounts();
	const accountIndex = accounts.findIndex(account => account.id === id);

	if (accountIndex === -1) {
		return false;
	}

	accounts.splice(accountIndex, 1);
	setStorageSync(StorageKeys.ACCOUNTS, accounts);

	return true;
}

/**
 * 批量删除账号
 * @param {Array<number>} ids 账号ID数组
 * @returns {number} 删除的账号数量
 */
export function deleteAccounts(ids) {
	if (!Array.isArray(ids) || ids.length === 0) {
		return 0;
	}

	const accounts = getAllAccounts();
	const filteredAccounts = accounts.filter(account => !ids.includes(account.id));
	
	const deletedCount = accounts.length - filteredAccounts.length;
	
	if (deletedCount > 0) {
		setStorageSync(StorageKeys.ACCOUNTS, filteredAccounts);
	}

	return deletedCount;
}

/**
 * 切换收藏状态
 * @param {number} id 账号ID
 * @returns {Object|null} 更新后的账号对象
 */
export function toggleFavorite(id) {
	const accounts = getAllAccounts();
	const accountIndex = accounts.findIndex(account => account.id === id);

	if (accountIndex === -1) {
		return null;
	}

	const account = accounts[accountIndex];
	account.isFavorite = !account.isFavorite;
	account.updatedAt = new Date().toISOString();
	account.lastModified = formatDateTime(new Date());

	accounts[accountIndex] = account;
	setStorageSync(StorageKeys.ACCOUNTS, accounts);

	return account;
}

/**
 * 初始化默认数据（用于演示或测试）
 */
export function initDefaultAccounts() {
	const accounts = getAllAccounts();
	
	// 检查是否已有示范数据（通过名称包含 "Demo" 来判断）
	const hasDemoData = accounts.some(account => account.name && account.name.includes('(Demo)'));
	
	// 如果账号列表为空或者没有示范数据，则添加两个示范数据
	if (accounts.length === 0 || !hasDemoData) {
		// 获取当前最大的ID，确保新数据的ID不冲突
		let maxId = 0;
		if (accounts.length > 0) {
			maxId = Math.max(...accounts.map(acc => acc.id || 0));
		}
		
		const defaultAccounts = [
			{
				id: maxId + 1,
				name: '微信 (Demo)',
				subtitle: 'WeiXin',
				account: 'WeiXin',
				password: 'password123',
				note: '',
				color: '#FF9500',
				category: 'all',
				isFavorite: true,
				tag: '社交媒体',
				createdAt: new Date().toISOString(),
				updatedAt: new Date().toISOString(),
				lastModified: formatDateTime(new Date())
			},
			{
				id: maxId + 2,
				name: 'STEAM (Demo)',
				subtitle: 'Play@gmail.com',
				account: 'Play@gmail.com',
				password: 'steam123',
				note: '',
				color: '#1E88E5',
				category: 'favorite',
				isFavorite: false,
				tag: '游戏娱乐',
				createdAt: new Date().toISOString(),
				updatedAt: new Date().toISOString(),
				lastModified: formatDateTime(new Date())
			}
		];
		
		// 合并现有数据和示范数据
		const allAccounts = [...accounts, ...defaultAccounts];
		setStorageSync(StorageKeys.ACCOUNTS, allAccounts);
		
		// 更新计数器
		const newCounter = Math.max(maxId + 2, getStorageSync(StorageKeys.ACCOUNT_COUNTER, 0));
		setStorageSync(StorageKeys.ACCOUNT_COUNTER, newCounter);
		
		return allAccounts;
	}
	return accounts;
}
